from rest_framework import serializers
from app01 import models
from rest_framework.exceptions import ValidationError
import hashlib
class UserSerializer(serializers.ModelSerializer):
    re_password = serializers.CharField(max_length=8,min_length=3,error_messages={
        'max_length':'确认密码最多8位',
        'min_length':'确认密码最少3位',
        'required':'确认密码不能为空',
    })
    class Meta:
        model = models.UserInfo
        fields = ['username','password','re_password','mobile','email']
        extra_kwargs = {
            'username':{'max_length':8,'min_length':3,
                        'error_messages':{
                            'max_length':'用户名最多8位',
                            'min_length':'用户名最少3位',
                            'required':'用户名不能为空'
                        }
                        },
            'password':{'max_length':8,'min_length':3,
                        'error_messages':{
                            'max_length':'密码最多8位',
                            'min_length':'密码最少3位',
                            'required':'密码不能为空'
                        }
                        },
            'mobile': {
                        'error_messages': {
                             'required': '手机号不能为空'
                         }
                         },
            'email': {
                         'error_messages': {
                             'required': '邮箱不能为空'
                         }
                         },
        }
    def validate(self,attrs):
        username = attrs.get('username').lower()
        if username.startswith('sb'):
            raise ValidationError('用户名不能以sb开头')
        password = attrs.get('password')
        re_password = attrs.get('re_password')
        if password == re_password:
            attrs.pop('re_password')
            header = '你好世界'.encode('utf-8')
            tail = '我来了'.encode('utf-8')
            password = password.encode('utf-8')
            hash_pwd = hashlib.md5(header + password + tail)
            attrs['password'] = hash_pwd
            models.UserInfo.objects.create(**attrs)
            return attrs
        else:
            raise ValidationError('两次密码不一致')
